%%%-------------------------------------------------------------------
%%% @author GAME4
%%% @copyright (C) 2018, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 15. 五月 2018 9:23
%%%-------------------------------------------------------------------
-module(hprose_http_handler).
-include("hprose.hrl").

%% API
-export([init/2]).

init(Req0, Opts) ->
  Method = cowboy_req:method(Req0),
  Resp = case Method of
    <<"POST">> ->
      {ok, PostValues, Req} = cowboy_req:read_body(Req0),
      handle_action(PostValues, Req, Opts);
    _ ->
      cowboy_req:reply(405, Req0)
  end,
  {ok, Resp, Opts}.

handle_action(<<?TAG_CALL, ?TAG_STRING, Stream/binary>>, Req, Opts) ->
  Resp = case proplists:get_value(module, Opts, hprose_handler) of
    undefined ->
      [?TAG_ERROR, hprose_writer:serialize({string, "Module Is Not Defined"})];
    Module ->
      [Value, TStream] = binary:split(Stream, <<?TAG_QUOTE>>),
      Len = binary_to_integer(Value),
      <<CallName:Len/binary, ?TAG_QUOTE, TStream1/binary>> = TStream,
      Args = hprose_reader:deserialize(TStream1),
      case Module:handle_call(CallName, Args) of
        {?TAG_RESULT, Result} -> [?TAG_RESULT | hprose_writer:serialize(Result)];
        {?TAG_ERROR, Reason} -> [?TAG_ERROR | hprose_writer:serialize(Reason)]
      end
  end,
  cowboy_req:reply(200, #{<<"content-type">> => <<"text/plain; charset=utf-8">>}, Resp, Req).
